using Catalog.Application.Brands.Interfaces;
using Catalog.Application.Contracts.DTOs;
using Microsoft.EntityFrameworkCore;

namespace Catalog.Infrastructure.Persistence.ReadServices;

public class BrandReadService : IBrandReadService
{
    private readonly CatalogDbContext _context;
    public BrandReadService(CatalogDbContext context)
    {
        _context = context;
    }

    public async Task<bool> ExistsAsync(Guid id)
    {
        return await _context.Brands
            .AsNoTracking()
            .AnyAsync(b => b.Id == id);
    }

    public async Task<BrandProfileDto?> GetByIdAsync(Guid id, CancellationToken cancellationToken = default)
    {
        return await _context.Brands
            .AsNoTracking()
            .Where(b => b.Id == id)
            .Select(b => new BrandProfileDto
            {
                Id = b.Id,
                Name = b.Name,
                Description = b.Description
            })
            .FirstOrDefaultAsync(cancellationToken);
    }

    public async Task<IEnumerable<BrandProfileDto>> GetListAsync(string? keyword = null, CancellationToken cancellationToken = default)
    {
        var query = _context.Brands.AsNoTracking().AsQueryable();

        if (!string.IsNullOrEmpty(keyword))
        {
            query = query.Where(b => b.Name.Contains(keyword));
        }

        return await query.Select(b => new BrandProfileDto
        {
            Id = b.Id,
            Name = b.Name,
            Description = b.Description
        }).ToListAsync(cancellationToken);
    }
}